﻿<cfcomponent name="data" ExtDirect="true">


		
<cffunction name="getInitForms" ExtDirect="true">   
<cftry>

<cfset retArr[1] = " ">
<cfset retArr[2] = " ">


<cfset retArr[3] = '<img src="' & session.root_undb & 'images/' & lcase(session.companycode) & '/' & session.site_bannerlogo & '" width="290" height="60">' >

<cfreturn retArr >
<cfcatch>
	<cfreturn cfcatch.detail & ' ' & cfcatch.message >
</cfcatch>			
</cftry>
</cffunction> 





<cffunction name="getTheFormsFromeFormid" ExtDirect="true"> 
<cfargument name="eformid" >
<cfargument name="actiontype" > 
<cftry>
<cfif actiontype eq "getmyeforms" >
	<cfset processData = ORMExecuteQuery("SELECT GRIDSCRIPT FROM EGRGEFORMS WHERE EFORMID = '#eformid#'", true ) >
	<cfset processData = replace(processData,"action: 'approveformnow',hidden: false,","action: 'approveformnow',hidden: true,") > 
	<cfset processData = replace(processData,"action: 'disapproveformnow',hidden: false,","action: 'disapproveformnow',hidden: true,") > 
	<cfset processData = replace(processData,"action: 'openformnow',hidden: false,","action: 'openformnow',hidden: true,") > 
<cfelseif actiontype eq "getneweforms" >
	<cfset processData = ORMExecuteQuery("SELECT GRIDSCRIPT FROM EGRGEFORMS WHERE EFORMID = '#eformid#'", true ) >
	<cfset processData = replace(processData,"isnew: false,ispending: false","isnew: true,ispending: false") >
	<cfset processData = replace(processData,"action: 'addeform',hidden: false,","action: 'addeform',hidden: true,") >
	<cfset processData = replace(processData,"action: 'copyeform',hidden: false,","action: 'copyeform',hidden: true,") >
	<cfset processData = replace(processData,"action: 'editeform',hidden: false,","action: 'editeform',hidden: true,") > 
	<cfset processData = replace(processData,"action: 'deleteeform',hidden: false,","action: 'deleteeform',hidden: true,") > 
	<cfset processData = replace(processData,"action: 'routeeform',hidden: false,","action: 'routeeform',hidden: true,") > 
<cfelseif actiontype eq "getpendingeforms" >
	<cfset processData = ORMExecuteQuery("SELECT GRIDSCRIPT FROM EGRGEFORMS WHERE EFORMID = '#eformid#'", true ) >
	<cfset processData = replace(processData,"isnew: false,ispending: false","isnew: false,ispending: true") >
	<cfset processData = replace(processData,"action: 'addeform',hidden: false,","action: 'addeform',hidden: true,") >
	<cfset processData = replace(processData,"action: 'copyeform',hidden: false,","action: 'copyeform',hidden: true,") >
	<cfset processData = replace(processData,"action: 'editeform',hidden: false,","action: 'editeform',hidden: true,") > 
	<cfset processData = replace(processData,"action: 'deleteeform',hidden: false,","action: 'deleteeform',hidden: true,") > 
	<cfset processData = replace(processData,"action: 'routeeform',hidden: false,","action: 'routeeform',hidden: true,") > 
</cfif>




<cfreturn processData >
<cfcatch>
	<cfreturn cfcatch.detail & ' ' & cfcatch.message >
</cfcatch>			
</cftry>
</cffunction>




<cffunction name="setIsreadTrue" ExtDirect="true" >
<cfargument name="eformid" >
<cfargument name="processid" >
<!---make the form isread as being read isread : true--->
<cftry>
	<cfset formRouterData = EntityLoad("EGINROUTERDETAILS", {PROCESSIDFK = #processid#}) >
	<cfloop array="#formRouterData#" index="routerIndex" > 
		<cfset formApproversData = EntityLoad("EGINAPPROVERDETAILS", {ROUTERIDFK =#routerIndex.getROUTERDETAILSID()#}) >
		<cfloop array="#formApproversData#" index="approverIndex" > 
			<cfset updateAction = EntityLoad("EGINAPPROVERDETAILS", {APPROVERDETAILSID =#approverIndex.getAPPROVERDETAILSID()#,ACTION='CURRENT',PERSONNELIDNO='#session.chapa#'}, true ) >
			<cfif isdefined("updateAction") >
				<cfset updateAction.setISREAD("true") >  
				<cfset EntitySave(updateAction) >
				<cfset ormflush() >
				<cfset updateCount = EntityLoad("EGINEFORMCOUNT", { EFORMID =#eformid#, PERSONNELIDNO = #session.chapa#}, true ) >
				<cfif isdefined("updateCount") >
					<cfif updateCount.getNEW() gt 0 >	
						<cfset currentCount = updateCount.getNEW() - 1 >
						<cfset updateCount.setNEW(currentCount) >
						<cfset currentCount = updateCount.getPENDING() + 1 >
						<cfset updateCount.setPENDING(currentCount) >
						<cfset EntitySave(updateCount) > 
						<cfset ormflush()>   
					</cfif> 
				</cfif>	
			</cfif>
			 
			
		</cfloop>
	</cfloop>
	
<cfset returnStruct = StructNew() >	
<!---execute after load process--->	
<cfset afterloadprocess = ORMExecuteQuery("SELECT AFTERLOAD
	  								       FROM EGRGEFORMS
	  								      WHERE EFORMID = '#eformid#'", true) >
<cfif afterloadprocess neq "NA" AND afterloadprocess neq "">
	<cfinclude template="../fielddefinition/afterload/#afterloadprocess#" > 
</cfif>	 
<!---end after load process, beforeload is found in actionform.cfc--->
						

<cfreturn returnStruct >
<cfcatch>
	<cfreturn cfcatch.detail & ' ' & cfcatch.message >
</cfcatch>			
</cftry>	
</cffunction>



<cffunction name="zeroapproveDisapprove" ExtDirect="true" > 
<cfargument name="eformid" >
<cftry>
	<cfset updateCount = EntityLoad("EGINEFORMCOUNT", { EFORMID =#eformid#, PERSONNELIDNO = #session.chapa#}, true ) >
	<cfif isdefined("updateCount") >	
		<cfset updateCount.setAPPROVED("0") >
		<cfset updateCount.setDISAPPROVED("0") >
		<cfset updateCount.setRETURNED("0") >    
		<cfset EntitySave(updateCount) >  
		<cfset ormflush()> 
	<cfelse>
	</cfif> 	
	
	
<cfreturn "successZero" >
<cfcatch>
	<cfreturn cfcatch.detail & ' ' & cfcatch.message >
</cfcatch>
</cftry>
</cffunction>


<cffunction name="deleteForm" ExtDirect="true" >
<cfargument name="eformid" >
<cfargument name="processid" > 
<cfargument name="level" >
<cfargument name="table" >
<cftry>
	
		
		
		
	
	<!---delete corrresponding process--->
	<cfquery name="rollbackProcessDetails" datasource="#session.global_dsn#" >
		DELETE FROM EGINFORMPROCESSDETAILS
		      WHERE PROCESSDETAILSID = '#processid#'
	</cfquery>
	
	<cftry>
		<cfset processDataB = EntityLoad("EGINROUTERDETAILS", {PROCESSIDFK=#processid#}, false ) >
		<cfloop array='#processDataB#' index='routerI' >
			
			<cfquery name="rollbackApproversDetails" datasource="#session.global_dsn#" >
				DELETE FROM EGINAPPROVERDETAILS
				      WHERE ROUTERIDFK = '#routerI.getROUTERDETAILSID()#'
			</cfquery>     
			
		</cfloop>
		
	
	<cfcatch>
	</cfcatch>
	</cftry>
	
	<cfquery name="rollbackRouterDetails" datasource="#session.global_dsn#" >
		DELETE FROM EGINROUTERDETAILS
		      WHERE PROCESSIDFK = '#processid#'
	</cfquery>
	<!---end delete corrresponding process--->
	
	<!---delete Main table item , this item--->
	<cfif level eq "G" >
		<cfset level = "#session.global_dsn#" >
	<cfelseif level eq "C" >
		<cfset level = "#session.company_dsn#" >			
	<cfelseif level eq "S" >
		<cfset level = "#session.subco_dsn#" >
	<cfelseif level eq "Q" >
		<cfset level = "#session.query_dsn#" >
	<cfelseif level eq "T" >
		<cfset level = "#session.transact_dsn#" >
	<cfelseif level eq "SD" >
		<cfset level = "#session.site_dsn#" >
	<cfelse>
		
	</cfif>
	
	<!---select the form data to be deleted and insert it to audit--->
	<cfset getMainTableID = ORMExecuteQuery("SELECT B.TABLENAME AS TABLENAME, 
												B.LEVELID AS LEVELID, 
												C.COLUMNNAME AS COLUMNNAME, 
												A.ISENCRYPTED AS ISENCRYPTED,
												A.BEFORESUBMIT AS BEFORESUBMIT,
												A.AFTERSUBMIT AS AFTERSUBMIT,
												A.AUDITTDSOURCE AS AUDITTDSOURCE,
												A.AUDITTNAME AS AUDITTNAME,
												A.LOGDBSOURCE AS LOGDBSOURCE,
												A.LOGTABLENAME AS LOGTABLENAME,
												A.LOGFILENAME AS LOGFILENAME
	  								       FROM EGRGEFORMS A,
	  								       		EGRGIBOSETABLE B,
	  								       		EGRGIBOSETABLEFIELDS C
	 								      WHERE EFORMID = '#eformid#' 
	 								      		AND A.EFORMID = B.EFORMIDFK 
	 								      		AND B.TABLEID = C.TABLEIDFK 
	 								      		AND C.XTYPE = 'id'
	 								         ", true) >
		
	<cfif trim(getMainTableID[1]) neq "" >
		<cfset firsttable  = getMainTableID[1] >
		<cfset firstlevel  = getMainTableID[2] >
		<cfset firstcolumn = getMainTableID[3] >
		<cfset isencrypted = getMainTableID[4] >
		<cfif arrayIsDefined(getMainTableID,7) >
			<cfset auditdatasource = getMainTableID[7] >
		<cfelse>
			<cfset auditdatasource = "NA" >
		</cfif>
		<cfif arrayIsDefined(getMainTableID,8) >
			<cfset audittablename  = getMainTableID[8] >
		<cfelse>
			<cfset audittablename = "NA" >
		</cfif>
		<cfif arrayIsDefined(getMainTableID,9) >
			<cfset logdatasource   = getMainTableID[9] >
		<cfelse>
			<cfset logdatasource = "NA" >
		</cfif>
		<cfif arrayIsDefined(getMainTableID,10) >
			<cfset logtablename    = getMainTableID[10] >
		<cfelse>
			<cfset logtablename = "NA" >
		</cfif>
		<cfif arrayIsDefined(getMainTableID,11) >
			<cfset logthefilename  = getMainTableID[11] >
		<cfelse>
			<cfset logthefilename = "NA" >
		</cfif>
		
	<cfelse>
		<cfthrow detail="Table has no id specified in table fields. At least one field type is an id type." >
	</cfif>
	
	

	<cfset allowAudit = ucase(auditdatasource) neq "NA" and trim(auditdatasource) neq "" and ucase(audittablename) neq "NA" and trim(audittablename) neq "" >
	<cfif allowAudit >
		<cfdbinfo datasource="#level#" 
				  name="theColumns"
				  type="columns"
				  table="#table#"
		>
		<cfset colArr = ArrayNew(1) >
		
		<cfloop query="theColumns" >
			<cfset ArrayAppend(colArr, COLUMN_NAME) >
		</cfloop>
		<cfset columnList = ArrayToList(colArr, ',') >
		
		<cfquery name="insertSelect" datasource="#auditdatasource#" >
			INSERT INTO  #audittablename# (#columnList#)
			      SELECT #columnList#
			        FROM #level#.#table#
			       WHERE EFORMID = '#eformid#' AND PROCESSID = '#processid#';
		</cfquery> 
		<cfquery name="updatePrev" datasource="#auditdatasource#" >
			UPDATE  #audittablename#
			   SET OPERATION = <cfqueryparam value="DELETED" cfsqltype="CF_SQL_VARCHAR">,
			       PERSONNELIDNO = <cfqueryparam value="#session.chapa#" cfsqltype="CF_SQL_VARCHAR">,
			       DATELASTUPDATE = <cfqueryparam value="#dateformat(now(), 'YYYY-MM-DD') & ' ' & timeformat(now(), 'HH:MM:SS')#" cfsqltype="CF_SQL_TIMESTAMP" >
			 WHERE EFORMID = '#eformid#' AND PROCESSID = '#processid#';
		</cfquery> 
	</cfif>


	<cfquery name="deleteForm" datasource="#level#" >
		DELETE FROM #table#
		      WHERE EFORMID = '#eformid#' AND PROCESSID = '#processid#'
	</cfquery> 
	
	<cfset allowLogDB = ucase(logdatasource) neq "NA" and trim(logdatasource) neq "" and ucase(logtablename) neq "NA" and trim(logtablename) neq "" >
	<cfif allowLogDB >
		<cfquery name='dynamicLog' datasource='#logdatasource#' >
			INSERT INTO #logtablename# ( 
									PERSONNELIDNO,
									DATELASTUPDATE,
									OPERATION
									) 
									
							VALUES ('#session.chapa#',
									'#dateformat(now(), "YYYY-MM-DD") & ' ' & timeformat(now(), "HH:MM:SS")#',
									'Deleted an eForm Object with an eForm id: #eformid# and process id: #processid#' )
		</cfquery>
	</cfif>
	
	<cfset allowLogToFile = ucase(logthefilename) neq "NA" and trim(logthefilename) neq "">
	<cfif allowLogToFile>
		<cflog file="#logthefilename#" text="Deleted an eForm Object with an eForm id: #eformid# and process id: #processid#"  >
	</cfif>
	
	<!---delete scheduled task assigned to the form if any--->
	<cftry>
		<cfschedule action="delete" task="process#processid#" >
	<cfcatch>
		<cftry>
			<cfschedule action="delete" task="process#processid#" >
			<cfcatch>
			</cfcatch>
		</cftry>
	</cfcatch>
	</cftry>
	
	<cftry>
		<cfschedule action="delete" task="router#processid#" >
	<cfcatch>
		<cftry>
			<cfschedule action="delete" task="router#processid#" >   
			<cfcatch>
			</cfcatch>
		</cftry>
	</cfcatch>
	</cftry> 

<cfreturn "success" >
<cfcatch>
	<cfreturn cfcatch.detail & ' ' & cfcatch.message >
</cfcatch>
</cftry>	
</cffunction>



<cffunction name="ReadNowDynamicApprover" ExtDirect="true"> 
	<cfargument name="page" >
	<cfargument name="start" >
	<cfargument name="limit" >
	<cfargument name="sort" >
	<cfargument name="filter" >
	<cfargument name="eformid" >   
	<cfargument name="routerid" >
		
 	<cfset where             = "()" >
	 
	 	    <cfset where             = " (" >
            <cfset tmpdatafield      = "" >
            <cfset tmpfilteroperator = "0" >
			
			<cftry>
			<cfset filter = deserializejson(filter) >	<!---Deserialize JSON string coz Router forgets to do the work on filter but not on sort--->
			<cfloop array=#filter# index="filterdata">
            	<cftry>
					<cfset filterdatafield = filterdata.field />
					<cfcatch>
						<cfbreak>   
					</cfcatch>
				</cftry>
            
            	<cfset filterdatafield = filterdata.field />
				<cfset filterdatafield = replace(filterdatafield, "_", ".") >
				<cfset filtervalue     = filterdata.value />
				<cfset filtertype      = filterdata.type />
				<cfif tmpdatafield EQ "" >
                <cfset tmpdatafield = filterdatafield >	
                <cfelseif tmpdatafield NEQ filterdatafield >
                	<cfset where = "#where# ) AND ( " >
                <cfelseif tmpdatafield EQ filterdatafield >
                	<cfif tmpfilteroperator EQ 0>
                    	<cfset where = "#where# AND " >
                    <cfelse>
                    	<cfset where = "#where# OR " >    
                    </cfif>
				</cfif>
                
                <cfif ucase(filtertype) EQ "STRING" >
					<cfset where = "#where##filterdatafield#  LIKE '%#filtervalue#%'" >   
				<cfelseif  ucase(filtertype) EQ "NUMERIC" >
					<cfset filtercondition = filterdata.comparison >
					<cfset expression = "#Ucase(Trim(filtercondition))#" >
               			<cfif expression  EQ "LT">
						   	<cfset where = "#where##filterdatafield#  < #filtervalue#">
						<cfelseif expression EQ "GT"> 	   
							<cfset where = "#where##filterdatafield#  > #filtervalue#">
						<cfelseif expression EQ "EQ"> 	   	
							<cfset where = "#where##filterdatafield#  = #filtervalue#">
						<cfelse>
					</cfif>
				<cfelseif  ucase(filtertype) EQ "DATE" >
					<cfset filtercondition = filterdata.comparison >
					<cfset expression = "#Ucase(Trim(filtercondition))#" >
					
						<cfset filtervalue = CreateODBCDateTime(filtervalue) />
               			<cfif expression  EQ "LT">
	               			<cfset where = "#where##filterdatafield#  < #filtervalue#">
						<cfelseif expression EQ "GT"> 	   
							<cfset where = "#where##filterdatafield#  > #filtervalue#">
						<cfelseif expression EQ "EQ"> 	   	
							<cfset where = "#where##filterdatafield#  = #filtervalue#">
						<cfelse>
							<cfset where = "#where##filterdatafield#  = #filtervalue#">
					    </cfif>
				<cfelse>
					<!---boolean--->
					<cfset where = "#where##filterdatafield#  LIKE '%#filtervalue#%'" >
				</cfif>
                <cfset tmpdatafield      = filterdatafield >
			</cfloop>
            	<cfcatch>
					<!---Do nothing here since filter is not a valid JSON string--->
				</cfcatch>
            </cftry>
            
            <cfset where = "#where#)" >
			<cfset where = Replace(where, "''", "'" , "all") />
			
			<cfif trim(where) NEQ "()">
				<cfset WHERE =  "AND #PreserveSingleQuotes(where)#" >
			<cfelse>
				<cfset WHERE = "" >
			</cfif> 
	
	  <!--- Order By Arguments/Contents --->
	  <cfset thecnt = 1 >
	  <cfloop array=#sort# index="sortdata">
	  	  <cfset ORDERBY = "#replace(sortdata.property, '_', '.')# #sortdata.direction#" >
	  	  <cfif thecnt EQ ArrayLen(sort) >
		  <cfelse>
	  	  	<cfset ORDERBY = ORDERBY & ',' >
		  </cfif>
		  <cfset thecnt = thecnt + 1 >
	  </cfloop>
	  <!--- End Order By Arguments/Contents --->


<cfset processData =ORMExecuteQuery("SELECT PERSONNELIDNO
									   FROM EGINDYNAMICAPPROVERS 
									   WHERE EFORMIDFK = '#eformid#' AND ROUTERIDFK = '#routerid#' AND OWNER='#session.chapa#'", false, {offset=#start#, maxResults=#limit#, timeout=60} ) >

<cfset resultArr = ArrayNew(1) >
<cfset rootstuct = StructNew() >

<cftry>
	<cfset countAll = ORMExecuteQuery("SELECT PERSONNELIDNO
									   FROM EGINDYNAMICAPPROVERS 
									   WHERE EFORMIDFK = '#eformid#' AND ROUTERIDFK = '#routerid#'")> 
<cfcatch>
</cfcatch>
</cftry>

<cfif isdefined('countAll') >
	<cfset rootstuct['totalCount'] = ArrayLen(countAll) > 
<cfelse>
    <cfset rootstuct['totalCount'] = 0 > 
</cfif>

<cfquery name="qryDetails" datasource="#session.company_dsn#" >
    SELECT FIRSTNAME, MIDDLENAME, LASTNAME, PERSONNELIDNO
      FROM #session.maintable#
     WHERE PERSONNELIDNO IN ('#ArrayToList(processData, "','")#') #WHERE# 
  ORDER BY #ORDERBY#
</cfquery>


	
	<!---query approver details and get an array of process id--->
										   
	<!---Creates an array of structure to be converted to JSON using serializeJSON--->
	<cfloop query="qryDetails" >
		<cfset tmpresult = StructNew() > <!---Creates new structure in every loop to be added to the array--->
		
		<cfset tmpresult['PERSONNELIDNO']   = PERSONNELIDNO >
		<cfset tmpresult['FIRSTNAME']      	= FIRSTNAME >
		<cfset tmpresult['MIDDLENAME']      = MIDDLENAME >
		<cfset tmpresult['LASTNAME']        = LASTNAME > 
		
		<cfset ArrayAppend(resultArr, tmpresult) >
		
	</cfloop>
	
	
	<cfset rootstuct['topics'] = resultArr > 
	<cfreturn rootstuct />	 
</cffunction>



<cffunction name="getThemes" ExtDirect="true" hint="This is used to load the company or user theme">   
<cftry>

<cfset retArr = ArrayNew(1) >

<cfset retArr[1] = '<img src="' & session.root_undb & 'images/' & lcase(session.companycode) & '/' & session.site_bannerlogo & '" width="290" height="60">' >

<cfreturn retArr >
<cfcatch>
	<cfreturn cfcatch.detail & ' ' & cfcatch.message >
</cfcatch>			
</cftry>
</cffunction> 
	
</cfcomponent>